package com.edmendst.xmall.handler;

import com.edmendst.xmall.dto.Region;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes(Region.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class RegionTypeHandler extends BaseTypeHandler<Region> {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Region parameter, JdbcType jdbcType)
            throws SQLException {
        try {
            ps.setString(i, objectMapper.writeValueAsString(parameter));
        } catch (JsonProcessingException e) {
            throw new SQLException("Error converting Region to JSON", e);
        }
    }

    @Override
    public Region getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return parseRegion(rs.getString(columnName));
    }

    @Override
    public Region getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return parseRegion(rs.getString(columnIndex));
    }

    @Override
    public Region getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return parseRegion(cs.getString(columnIndex));
    }

    private Region parseRegion(String json) {
        if (json == null || json.isEmpty()) {
            return null;
        }
        try {
            return objectMapper.readValue(json, Region.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Error parsing Region JSON: " + json, e);
        }
    }
}